package cn.zjnu.controller;

import cn.zjnu.domain.Cart;
import cn.zjnu.domain.Goods;
import cn.zjnu.service.ShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shopping")
public class ShoppingController {
    @Autowired
    private ShoppingService shoppingService;
    @GetMapping("/getAll")
    public Result getAll(){
        List<Goods> goodsList = shoppingService.showGoodsMsg();
        Integer code = !goodsList.isEmpty() ? Code.GET_OK:Code.GET_ERR;
        String msg = !goodsList.isEmpty() ? "获取数据成功":"获取数据失败";
        return new Result(goodsList,code,msg);
    }
    @GetMapping("/getAll/{id}")
    public Result getAllById(@PathVariable Integer id){
        List<Goods> goodsList = shoppingService.showGoodsMsgById(id);
        Integer code = !goodsList.isEmpty() ? Code.GetGoodsByUserId_OK:Code.GetGoodsByUserId_ERR;
        String msg = !goodsList.isEmpty() ? "获取数据成功":"获取数据失败";
        return new Result(goodsList,code,msg);
    }
    @PostMapping("/add")
    public Result addGoods(@RequestBody Cart cart){
        boolean flag = shoppingService.addGoods(cart);
        String msg = flag ? "添加到购物车成功":"添加到购物车失败";
        return new Result(cart,flag ? Code.AddGoods_OK:Code.AddGoods_ERR,msg);
    }
    @PutMapping("/plus")
    public Result plusGoods(@RequestBody Cart cart){
        boolean flag = shoppingService.plusGoods(cart);
        String msg = flag ? "增加商品成功":"增加商品失败";
        return new Result(cart,flag ? Code.GoodsPlus_OK: Code.GoodsPlus_ERR,msg);
    }
    @PutMapping("/reduce")
    public Result reduceGoods(@RequestBody Cart cart){
        boolean flag = shoppingService.reduceGoods(cart);
        String msg = flag ? "减少商品成功":"减少商品失败";
        return new Result(cart,flag ? Code.GoodsReduce_OK: Code.GoodsReduce_ERR,msg);
    }
    @DeleteMapping("/delete")
    public Result deleteGoods(@RequestBody Cart cart){
        boolean flag = shoppingService.deleteGoodsInCart(cart);
        String msg = flag ? "删除商品成功":"删除商品失败";
        return new Result(cart,flag ? Code.GoodsDelete_OK: Code.GoodsDelete_ERR,msg);
    }
    @GetMapping("/settle/{user_id}")
    public Result showAccounts(@PathVariable Integer user_id){
        Double total_money = shoppingService.showAccount(user_id);
        return new Result(total_money,Code.GetAccount_OK,"查询成功");
    }
    @PutMapping("/settle/{id}")
    public Result settleAccounts(@PathVariable Integer id){
        boolean flag = shoppingService.settleAccount(id);
        String msg = flag ? "结账成功":"结账失败";
        return new Result(id,flag?Code.SettleAccount_OK: Code.SettleAccount_ERR,msg);
    }

}
